package com.suxin.shiro.jwt.realm;

import com.suxin.shiro.jwt.token.JwtToken;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.Arrays;

/**
 * @author Tang
 * @classname JwtRealm
 * @description [  ]
 * @date 2021/3/21 22:37
 */
public class JwtRealm extends AuthorizingRealm {

    @Override
    public String getName() {
        return JwtRealm.class.getName();
    }

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("===================jwt授权开始======================");
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.addRoles(Arrays.asList("admin","user"));
        return authorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("===================jwt认证开始======================");
        JwtToken customizedToken = (JwtToken) token;
        Object principal = customizedToken.getPrincipal();
        // todo 查库，查出密码
        Object credentials = customizedToken.getCredentials();
        return new SimpleAuthenticationInfo(principal,credentials,this.getName());
    }
}